import axios from "axios";
import { ElMessage } from "element-plus";
import router from '../router';

const instance = axios.create({
    baseURL: '/api',  
    timeout: 30000
})

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('Authorization')
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        if (token) {
            config.headers.Authorization = token;  // 设置请求头
        }
        return config
    },
    (err) => {
        Promise.reject(err)
    }
)

//响应拦截器
instance.interceptors.response.use(
    result => {
        if (result.data.code === 200) {
            return result.data
        } else {
            ElMessage.error(result.data.message ? result.data.message : '服务异常')
            return Promise.reject(result.data)
        }

    }, 
    error => {
        if(error.response.status === 401){
            ElMessage.error('登录失效，请重新登录')
            router.push('/login')
        }else{
            ElMessage.error('服务异常，请重试')
        }
        return Promise.reject(error)
    });

export default instance

